'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import { projectApi, api } from '@/lib/api';
import { TaskCard } from '@/components/project/task-card';
import BoardColumn from '@/components/project/board-column';
import AppHeader from '@/components/ui/app-header';
import { Button } from '@/components/ui/button';
import { PlusIcon } from '@heroicons/react/24/outline';
import { useRouter } from 'next/navigation';
import { toast } from '@/components/ui/use-toast';
import { taskStatusToApiFormat, taskStatusFromApiFormat } from '@/lib/utils';
import { TASK_STATUS } from '@/lib/constants';
import { Task } from '@/hooks/use-task';

// 任务状态类型
type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'REVIEW' | 'DONE';

// 任务类型定义
interface Project {
  id: string;
  name: string;
  description?: string | null;
}

export default function ProjectBoardPage() {
  const { id } = useParams<{ id: string }>();
  const { data: session, status } = useSession();
  const router = useRouter();
  const [project, setProject] = useState<Project | null>(null);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [updateLoading, setUpdateLoading] = useState(false);

  // 任务分组
  const todoTasks = tasks.filter(task => 
    taskStatusFromApiFormat(task.status) === TASK_STATUS.TODO || 
    task.status === 'TODO'
  );
  const inProgressTasks = tasks.filter(task => 
    taskStatusFromApiFormat(task.status) === TASK_STATUS.IN_PROGRESS || 
    task.status === 'IN_PROGRESS'
  );
  const reviewTasks = tasks.filter(task => 
    taskStatusFromApiFormat(task.status) === TASK_STATUS.REVIEW || 
    task.status === 'REVIEW'
  );
  const doneTasks = tasks.filter(task => 
    taskStatusFromApiFormat(task.status) === TASK_STATUS.DONE || 
    task.status === 'DONE'
  );

  // 获取项目信息和任务
  useEffect(() => {
    const fetchProjectData = async () => {
      if (status !== 'authenticated' || !id) return;
      
      setLoading(true);
      setError(null);
      
      try {
        // 获取项目详情
        const projectData = await projectApi.getProject(id as string);
        setProject(projectData);
        
        // 获取项目任务
        const tasksData = await projectApi.getProjectTasks(id as string);
        console.log('获取到的任务数据:', tasksData);
        
        // 确保任务数据是数组
        if (Array.isArray(tasksData)) {
          setTasks(tasksData);
        } else if (tasksData && Array.isArray(tasksData.data)) {
          // 如果返回的是 { data: [...] } 格式
          setTasks(tasksData.data);
        } else {
          console.warn('任务数据格式不符合预期:', tasksData);
          setTasks([]);
        }
      } catch (err) {
        console.error('获取项目数据失败:', err);
        setError('无法加载项目数据，请重试');
      } finally {
        setLoading(false);
      }
    };
    
    fetchProjectData();
  }, [id, status]);

  // 处理任务拖拽
  const handleDragEnd = async (result: any) => {
    if (!result.destination) return;
    
    const { draggableId, source, destination } = result;
    
    // 如果没有移动位置，不做处理
    if (
      source.droppableId === destination.droppableId &&
      source.index === destination.index
    ) {
      return;
    }
    
    // 找到被拖拽的任务
    const task = tasks.find(t => t.id === draggableId);
    if (!task) return;
    
    // 更新任务状态
    const newStatus = destination.droppableId as TaskStatus;
    
    // 转换为API格式
    const apiStatus = taskStatusToApiFormat(newStatus);
    
    // 更新本地状态
    const updatedTasks = tasks.map(t => 
      t.id === draggableId ? { ...t, status: apiStatus } : t
    );
    setTasks(updatedTasks);
    
    // 直接使用底层API调用更新任务状态，使用带id参数的URL
    try {
      await api.put(`/task?id=${draggableId}`, { status: apiStatus });
      
      // 显示成功消息
      toast({
        title: "任务状态已更新",
        description: "任务已移动到新状态",
      });
    } catch (err) {
      console.error('更新任务状态失败:', err);
      // 恢复原状态
      setTasks(tasks);
      
      // 显示错误消息
      toast({
        title: "操作失败",
        description: "更新任务状态失败，请重试",
        variant: "destructive",
      });
    }
  };

  // 处理任务状态变更
  const handleTaskStatusChange = async (task: Task, newStatus: string) => {
    try {
      setUpdateLoading(true);
      
      // 转换为API格式
      const apiStatus = taskStatusToApiFormat(newStatus);
      
      // 直接使用底层API调用更新任务状态，使用带id参数的URL
      await api.put(`/task?id=${task.id}`, { status: apiStatus });
      
      // 更新本地状态
      setTasks(currentTasks => {
        const updatedTasks = [...currentTasks];
        const taskIndex = updatedTasks.findIndex(t => t.id === task.id);
        
        if (taskIndex !== -1) {
          updatedTasks[taskIndex] = {
            ...updatedTasks[taskIndex],
            status: apiStatus
          };
        }
        
        return updatedTasks;
      });
      
      // 显示成功消息
      toast({
        title: "任务状态已更新",
        description: newStatus === TASK_STATUS.DONE ? "任务已标记为完成" : "任务状态已变更",
      });
    } catch (error) {
      console.error('更新任务状态失败:', error);
      toast({
        title: "操作失败",
        description: "更新任务状态失败，请重试",
        variant: "destructive",
      });
    } finally {
      setUpdateLoading(false);
    }
  };

  // 创建新任务
  const handleCreateTask = () => {
    router.push(`/task/new?projectId=${id}`);
  };

  // 空列提示组件
  const EmptyColumnPlaceholder = ({ columnId }: { columnId: string }) => (
    <div className="flex flex-col items-center justify-center py-4 px-2 text-center text-gray-400 text-sm h-24">
      <p>没有任务</p>
      <button 
        className="mt-2 text-xs text-blue-500 hover:underline"
        onClick={handleCreateTask}
      >
        创建新任务
      </button>
    </div>
  );

  if (loading) {
    return (
      <div className="container py-6">
        <div className="flex justify-center items-center h-64">
          <div className="animate-pulse">正在加载看板...</div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container py-6">
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative">
          <strong className="font-bold">错误：</strong>
          <span className="block sm:inline">{error}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="container py-6">
      <AppHeader
        title={project?.name ? `${project.name} - 看板` : '项目看板'}
        subtitle={project?.description || '管理和跟踪项目任务'}
        actions={
          <Button onClick={handleCreateTask}>
            <PlusIcon className="w-4 h-4 mr-1" />
            新任务
          </Button>
        }
      />
      
      {tasks.length === 0 ? (
        <div className="mt-8 bg-white p-8 rounded-lg shadow-sm text-center">
          <h3 className="text-lg font-medium text-gray-700 mb-2">项目中还没有任务</h3>
          <p className="text-gray-500 mb-4">点击下面的按钮来创建您的第一个任务</p>
          <Button onClick={handleCreateTask}>
            <PlusIcon className="w-5 h-5 mr-2" />
            创建第一个任务
          </Button>
        </div>
      ) : (
        <DragDropContext onDragEnd={handleDragEnd}>
          <div className="mt-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* 待处理列 */}
            <BoardColumn 
              title="待处理" 
              count={todoTasks.length} 
              id="TODO"
            >
              <Droppable droppableId="TODO">
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    className="space-y-3 min-h-[200px]"
                  >
                    {todoTasks.length > 0 ? todoTasks.map((task, index) => (
                      <Draggable key={task.id} draggableId={task.id} index={index}>
                        {(provided) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <TaskCard task={task} projectId={id as string} onStatusChange={handleTaskStatusChange} />
                          </div>
                        )}
                      </Draggable>
                    )) : (
                      <EmptyColumnPlaceholder columnId="TODO" />
                    )}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </BoardColumn>
            
            {/* 进行中列 */}
            <BoardColumn 
              title="进行中" 
              count={inProgressTasks.length} 
              id="IN_PROGRESS"
            >
              <Droppable droppableId="IN_PROGRESS">
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    className="space-y-3 min-h-[200px]"
                  >
                    {inProgressTasks.length > 0 ? inProgressTasks.map((task, index) => (
                      <Draggable key={task.id} draggableId={task.id} index={index}>
                        {(provided) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <TaskCard task={task} projectId={id as string} onStatusChange={handleTaskStatusChange} />
                          </div>
                        )}
                      </Draggable>
                    )) : (
                      <EmptyColumnPlaceholder columnId="IN_PROGRESS" />
                    )}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </BoardColumn>
            
            {/* 审核中列 */}
            <BoardColumn 
              title="审核中" 
              count={reviewTasks.length} 
              id="REVIEW"
            >
              <Droppable droppableId="REVIEW">
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    className="space-y-3 min-h-[200px]"
                  >
                    {reviewTasks.length > 0 ? reviewTasks.map((task, index) => (
                      <Draggable key={task.id} draggableId={task.id} index={index}>
                        {(provided) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <TaskCard task={task} projectId={id as string} onStatusChange={handleTaskStatusChange} />
                          </div>
                        )}
                      </Draggable>
                    )) : (
                      <EmptyColumnPlaceholder columnId="REVIEW" />
                    )}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </BoardColumn>
            
            {/* 已完成列 */}
            <BoardColumn 
              title="已完成" 
              count={doneTasks.length} 
              id="DONE"
            >
              <Droppable droppableId="DONE">
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.droppableProps}
                    className="space-y-3 min-h-[200px]"
                  >
                    {doneTasks.length > 0 ? doneTasks.map((task, index) => (
                      <Draggable key={task.id} draggableId={task.id} index={index}>
                        {(provided) => (
                          <div
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <TaskCard task={task} projectId={id as string} onStatusChange={handleTaskStatusChange} />
                          </div>
                        )}
                      </Draggable>
                    )) : (
                      <EmptyColumnPlaceholder columnId="DONE" />
                    )}
                    {provided.placeholder}
                  </div>
                )}
              </Droppable>
            </BoardColumn>
          </div>
        </DragDropContext>
      )}
    </div>
  );
} 